package com.isyscore.os.metadata.listener;

import com.isyscore.boot.login.dto.ApiRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;


/**
 * openApi 注册
 *
 * @author liy
 * @date 2022-10-25 14:07
 */

@Component
@RequiredArgsConstructor
@Order(1)
@Slf4j
public class OrchestrationListener implements ApplicationRunner {
    @Value("${service.orchestration}")
    private String orchestration;
    private final ResourceLoader resourceLoader;
    @Override
    public void run(ApplicationArguments args) throws InterruptedException {

        new Thread(() -> {
            try {
                InputStream inputStream = this.getClass().getResourceAsStream("/file/openApi.json");
                String apiJson = getContent(inputStream);
                OkHttpClient client = new OkHttpClient().newBuilder().build();
                MediaType mediaType = MediaType.parse("application/json");
                RequestBody body = RequestBody.create(mediaType, apiJson);
                String token = ApiRequest.getInstance().refreshToken();
                log.info("token:===>"+token);
                Request request = new Request.Builder()
                        .url(orchestration+"?type=UDMP")
                        .method("POST", body)
                        .addHeader("token",token)
                        .addHeader("Content-Type", "application/json")
                        .build();

                Response response = client.newCall(request).execute();
                if(!response.isSuccessful()){
                    log.error("openApi注册失败{}", orchestration);
                }
                log.info("注册返回信息:{}", response.body().string());
            } catch (Exception e) {
                log.error("openApi注册失败{}", orchestration);
                e.printStackTrace();
            }
        }).start();
    }

    private String getContent(InputStream inputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
            stringBuilder.append("\n");
        }

        reader.close();
        return stringBuilder.toString();
    }
}




